package tools

import (
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"net"
	"os"
)

var Searcher *xdb.Searcher

////go:embed db/*
//var dbFiles embed.FS

// 创建ip搜索
func init() {

	dbPath := "./static/db/ip2region.xdb"
	content, err := os.ReadFile(dbPath)
	if err != nil {
		panic(err)
	}

	// 2、用全局的 cBuff 创建完全基于内存的查询对象。
	Searcher, err = xdb.NewWithBuffer(content)
	if err != nil {
		fmt.Printf("failed to create searcher with content: %s\n", err)
		return
	}
}

func ParseIp(myip string) string {
	region, _ := Searcher.SearchByStr(myip)
	return region
}

// 获取出站IP地址
func GetOutboundIP() (net.IP, error) {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)

	return localAddr.IP, nil
}
